#include "datamodel.h"
#include <QDateTime>
#include <QTime>
#include <QtAlgorithms>

DataModel::DataModel(QObject *parent)
	: QAbstractTableModel(parent)
{
}

int DataModel::rowCount(const QModelIndex &parent) const {
	Q_UNUSED(parent);
	return m_list.count();
}

int DataModel::columnCount(const QModelIndex &parent) const {
	Q_UNUSED(parent);
	return 3;
}

QVariant DataModel::data(const QModelIndex &index, int role) const {
	switch( role ){
	case Qt::DisplayRole:
		if( index.column() == 0 ){
			QString title = m_list.at( index.row() ).title;
			return title.replace("&quot;","\"");
		}
		if(index.column() == 2 ){
			QDateTime time = QDateTime::fromTime_t(
										m_list.at( index.row() ).timestamp );
			QDateTime midnight = QDateTime::currentDateTime();
			midnight.setTime( QTime(0,0) );
			if( time < midnight )
				return time.toString("yyyy-MM-dd hh:mm:ss");
			else
				return time.toString("hh:mm:ss");
		}
		break;
	case Qt::UserRole:
		return QVariant( m_list.at( index.row() ).readed );

	case (Qt::UserRole + 1):
		return QVariant( m_list.at( index.row() ).id );
	}

	return QVariant();
}

QVariant DataModel::headerData(int section, Qt::Orientation orientation,
							   int role) const
{
	if( Qt::DisplayRole != role )
		return QAbstractTableModel::headerData( section, orientation, role );

	if( Qt::Vertical == orientation){
		return QVariant( QString::number( section ) );
	}

	//for horizontal
	switch(section){
	case 0:
		return tr("Tytuł");
	case 2:
		return tr("Data publikacji");
	}


	return QVariant();
}

void DataModel::fillData(QSqlQuery &query){
	m_list.clear();

	while( query.next() ){
		TableEntry entry;
		entry.id = query.value(0).toUInt();
		entry.title = query.value(1).toString();
		entry.readed = query.value(2).toBool();
		entry.timestamp = query.value(3).toUInt();
		m_list.push_back( entry );
	}
	reset();
}

void DataModel::itemReaded(const QModelIndex &index){
	if( m_list.at(index.row()).readed == true )
		return;

	m_list[ index.row() ].readed = true;

	emit markAsReaded( m_list.at(index.row()).id, true );
}

void DataModel::itemUnreaded(const QModelIndex &index){
	if( m_list.at(index.row()).readed == false )
		return;

	m_list[ index.row() ].readed = false;

	emit markAsReaded( m_list.at(index.row()).id, false );
}

void DataModel::itemDeleted(QList<int> indexes){
	beginResetModel();
	qSort(indexes.begin(), indexes.end(), qGreater<int>());

	foreach(int index, indexes){
		emit markAsDeleted( index, true );

		m_list.removeAt( index );
	}

	endResetModel();
}
